/*	talmud - The TALMUD roguelike
 * Copyright (C) 2012, talmud contributors
 *
 *  This program is free software; you can redistribute it and/or modify it
 *  under the terms of Version 2 of the GNU General Public License as published
 *  by the Free Software Foundation.
 *
 *  This program is distributed in the hope that it will be useful, but WITHOUT
 *  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *  FITNESS FOR A PARTICULAR PURPOSE. See Version 2 of the GNU General Public
 *  License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "config.h"
#include "talmud.h"

void SetupDefaultConfig(void)
{
	inkey[K_MOVE1] = '1';
	inkey[K_MOVE2] = '2';
	inkey[K_MOVE3] = '3';
	inkey[K_MOVE4] = '4';
	inkey[K_MOVE6] = '6';
	inkey[K_MOVE7] = '7';
	inkey[K_MOVE8] = '8';
	inkey[K_MOVE9] = '9';
	inkey[K_MOVEUP] = '<';
	inkey[K_MOVEDN] = '>';
	inkey[K_INV] = 'i';
	inkey[K_WAIT] = '.';
	inkey[K_PICKUP] = ',';
	inkey[K_DROP] = 'd';
	inkey[K_ZAP] = 'z';
	inkey[K_QUAFF] = 'q';
	inkey[K_WIELD] = 'w';
	inkey[K_WEAR] = 'W';
	inkey[K_TAKEOFF] = 'T';
}

uint8_t LoadConfig(void)
{
	FILE *filePtr;
	char path[128];
	char buffer[128];
	char *line;
	int8_t offset;
	uint8_t key;
	int result;

	if (strlen(getenv("HOME")) > (128 - 16))
	{
		printf("$HOME is too long.\n");
		return 1;
	}
	sprintf(path, "%s/.talmudrc", getenv("HOME"));
	filePtr = fopen(path, "rb");
	if (!filePtr)
	{
		return 1;
	}

	while (fgets(line, 128, filePtr))
	{
		offset = 0;
		line = buffer;
		while (line[0] == ' ' || line[0] == '\t')
		{
			offset++;
			line = &buffer[offset];
		}
		if (strstr(line, "#") == line || strstr(line, "//") == line || strstr(line, "\"") == line)
		{
			continue;
		}
		else if (strstr(line, "map") == line)
		{
			result = sscanf(line, "map%hhi %hhi", &offset, &key);
			if (result != 2 || offset < 0 || offset >= INKEY_COUNT)
			{
				AddMsg("Malformed 'map' directive in .talmudrc");
				continue;
			}
			inkey[offset] = key;
		}
	}

	fclose(filePtr);

	return 0;
}
